package com.lujianfei.ann.base;

import java.awt.event.ActionListener;
import java.util.List;

import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

import com.lujianfei.lib.window.BaseMdiWindow;
import com.lujianfei.lib.window.BaseWindow;

public abstract class BaseMenuWindow extends BaseMdiWindow {

	public BaseMenuWindow() {
		super(true);
	}

	@Override
	protected void initMenu() {
		JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);
		List<MenuBean> menuBeans = getMenuBean();
		if (null == menuBeans) {
			return;
		}
		for (MenuBean bean : menuBeans) {
			JMenu menu = new JMenu(bean.name);
			menu.setMnemonic(bean.mnemonic);
			menuBar.add(menu);
			if (bean.hasChild()) {
				for (MenuBean menuChild : bean.childs) {
					JMenuItem menuItem = new JMenuItem(menuChild.name);
					if (' ' != menuChild.mnemonic) {
						menuItem.setMnemonic(menuChild.mnemonic);
					}
					menuItem.addActionListener(menuChild.actionListener);
					menu.add(menuItem);
					if (menuChild.addSeparator) {
						menu.addSeparator();
					}
				}
			}
		}
	}

	protected abstract List<MenuBean> getMenuBean();

	public static class MenuBean {

		private boolean addSeparator;
		private String name;
		private char mnemonic;
		private ActionListener actionListener;

		private List<MenuBean> childs;

		public MenuBean(String name, char mnemonic, List<MenuBean> childs, boolean addSeparator,
				ActionListener actionListener) {
			super();
			this.name = name;
			this.mnemonic = mnemonic;
			this.childs = childs;
			this.addSeparator = addSeparator;
			this.actionListener = actionListener;
		}

		public boolean hasChild() {
			return null != childs && childs.size() > 0;
		}

		public static class Builder {

			private boolean addSeparator;
			private String name;
			private char mnemonic;
			private ActionListener actionListener;

			private List<MenuBean> childs;

			public Builder() {
				mnemonic = ' ';
			}

			public Builder setName(String name) {
				this.name = name;
				return this;
			}

			public Builder addSeparator() {
				this.addSeparator = true;
				return this;
			}

			public Builder setMnemonic(char mnemonic) {
				this.mnemonic = mnemonic;
				return this;
			}

			public Builder setActionListener(ActionListener actionListener) {
				this.actionListener = actionListener;
				return this;
			}

			public Builder setChilds(List<MenuBean> childs) {
				this.childs = childs;
				return this;
			}

			public MenuBean create() {
				return new MenuBean(name, mnemonic, childs, addSeparator, actionListener);
			}
		}
	}
}
